package com.jinmdz.app.api.service;

import com.jinmdz.app.api.constant.CacheKey;
import com.jinmdz.app.api.model.rockey.KeyResult;
import com.jinmdz.app.api.wrapper.LicenseWrapper;
import com.jinmdz.app.api.wrapper.RockeyWrapper;
import com.jinmdz.app.dao.dao.GlobalDao;
import com.jinmdz.fmis.common.util.DataUtil;
import com.jinmdz.fmis.core.exception.ActionException;
import com.jinmdz.fmis.core.license.CertificateExtraModel;
import com.jinmdz.fmis.core.util.JacksonUtil;
import com.jinmdz.fmis.core.util.LogUtil;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 身份验证Service
 *
 * @author LiCongLu
 * @date 2020-04-17 14:43
 */
@Service("authorizeService")
public class AuthorizeService {

    @Resource
    private LicenseWrapper licenseWrapper;

    @Resource
    private RockeyWrapper rockeyWrapper;

    @Resource
    private GlobalDao globalDao;

    @Resource
    private Cache applicationCache;

    /**
     * Bean初始化函数
     *
     * @param
     * @return
     * @author LiCongLu
     * @date 2020-04-17 17:29
     */
    // @PostConstruct
    public void initMethod() throws ActionException {
        KeyResult result = authorizeTask();
        // 验证成功，输出成功信息
        if (result.isSuccess()) {
            LogUtil.info(result.getMessage());
            return;
        }

        // 验证未成功，输出错误信息，抛出异常，阻止启动
        LogUtil.info("加密狗验证失败：" + result.getMessage());
        // 当抛出异常时，可阻止接口系统启动
        // throw new ActionException("加密狗验证失败：" + result.getMessage());
    }

    /**
     * 执行身份验证任务
     *
     * @param
     * @return
     * @author LiCongLu
     * @date 2020-04-17 14:45
     */
    public KeyResult authorizeTask() {
        KeyResult result = authorizeResult();
        LogUtil.line("定时任务执行结果：" + JacksonUtil.obj2Json(result));
        applicationCache.put(CacheKey.AUTHORIZE_LICENSE_ROCKEY, result);
        return result;
    }

    /**
     * 验证执行身份许可证及加密狗
     *
     * @param
     * @return
     * @author LiCongLu
     * @date 2020-04-17 14:47
     */
    private KeyResult authorizeResult() {
        // 先验证许可证书
        if (!licenseWrapper.verifyLicense()) {
            return new KeyResult()
                    .setMessage("许可证书无效," + licenseWrapper.getMessage());
        }

        // 获取加密狗相关信息
        CertificateExtraModel extraModel = licenseWrapper.getExtraModel();
        // 判断许可内是否配置了加密狗信息
        if (extraModel != null && DataUtil.valid(extraModel.getSecretKey())) {
            // 验证加密狗秘钥信息
            return rockeyWrapper.checkSoftLicense(extraModel, globalDao.getNowForDate());
        }

        // 返回正确许可结果
        return new KeyResult()
                .setSuccess(true)
                .setMessage("许可证书有效," + licenseWrapper.getMessage());
    }
}
